package com.block.datapush.form.item;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.item.util.DianDai3Util;
import com.block.datapush.form.item.util.DianDaiUtil;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 点贷
 */
@Service
public class DianDaiTHREEPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    /**
     * /api/Infos/userExist
     *
     * @param formInfo
     * @param memberExtInfo
     * @return
     */
    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

        String queryUrl = formInfo.getQueryUrl();
        String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

        Map<String, Object> bizParamMap = new HashMap<>();
        bizParamMap.put("phone_md5", mobileMd5);
        bizParamMap.put("sex",memberExtInfo.getSex() == 1 ? 1300 : 1301);
        bizParamMap.put("age", memberExtInfo.getAge());
        bizParamMap.put("province",Integer.valueOf(memberExtInfo.getCityCode()));
        bizParamMap.put("loan", DianDai3Util.getLoanAmount(memberExtInfo.getLoanAmount()));
        bizParamMap.put("has_social",DianDai3Util.getshebao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("has_fund",DianDai3Util.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("life_insurance",DianDai3Util.getbaoxian(memberExtInfo.getInsurance()));
        bizParamMap.put("house_property",DianDai3Util.gethouse(memberExtInfo.getHouse()));
        bizParamMap.put("car_property",DianDai3Util.getcar(memberExtInfo.getCar()));
        bizParamMap.put("zhima_credit",DianDai3Util.getZhiMa(memberExtInfo.getZhimaScore()));
        bizParamMap.put("credit_card_limit",900);
        bizParamMap.put("huabei",DianDai3Util.getHuaBei(memberExtInfo.getHuabei()));
        bizParamMap.put("baitiao",DianDai3Util.getBaiTiao(memberExtInfo.getBaitiao()));
        bizParamMap.put("enterprise_license",DianDai3Util.getjob(memberExtInfo.getJob()));
        bizParamMap.put("credit_history",DianDai3Util.getyuqi(memberExtInfo.getYuqi()));
        String jsonParamMap = JSON.toJSONString(bizParamMap);

        Long timestamp = System.currentTimeMillis();

        String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
        String content = this.encryptBizParam(jsonParamMap,formInfo.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel", formInfo.getApiKey());
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("content", content);


        log.info("【点贷】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}",
                queryUrl, JSON.toJSONString(bizParamMap),JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【点贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");

        if (StrUtil.equals("200", String.valueOf(status))) {
            return true;
        }
        return false;
    }

    /**
     * /api/Infos/receive
     *
     * @param formInfo
     * @param memberExtInfo
     * @param orderNo
     * @param jsonObject
     * @return
     */
    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

        String queryUrl = formInfo.getRequestUrl();

        Map<String, Object> bizParamMap = new HashMap<>();

        bizParamMap.put("apply_name", memberExtInfo.getUsername());
        bizParamMap.put("id_card", memberExtInfo.getIdCard());
        bizParamMap.put("phone", memberExtInfo.getMobile());
        bizParamMap.put("phone_md5", SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase());
        bizParamMap.put("age", memberExtInfo.getAge());
        bizParamMap.put("sex", memberExtInfo.getSex() == 1 ? 1300 : 1301);
        bizParamMap.put("province",Integer.valueOf(memberExtInfo.getCityCode()));
        bizParamMap.put("loan",DianDai3Util.getLoanAmount(memberExtInfo.getLoanAmount()));
        bizParamMap.put("has_social",DianDai3Util.getshebao(memberExtInfo.getSocialInsurance()));
        bizParamMap.put("has_fund",DianDai3Util.getGjj(memberExtInfo.getGjj()));
        bizParamMap.put("life_insurance",DianDai3Util.getbaoxian(memberExtInfo.getInsurance()));
        bizParamMap.put("house_property",DianDai3Util.gethouse(memberExtInfo.getHouse()));
        bizParamMap.put("car_property",DianDai3Util.getcar(memberExtInfo.getCar()));
        bizParamMap.put("zhima_credit",DianDai3Util.getZhiMa(memberExtInfo.getZhimaScore()));
        bizParamMap.put("credit_card_limit",900);
        bizParamMap.put("huabei",DianDai3Util.getHuaBei(memberExtInfo.getHuabei()));
        bizParamMap.put("baitiao",DianDai3Util.getBaiTiao(memberExtInfo.getBaitiao()));
        bizParamMap.put("enterprise_license",DianDai3Util.getjob(memberExtInfo.getJob()));
        bizParamMap.put("credit_history",DianDai3Util.getyuqi(memberExtInfo.getYuqi()));

        Long timestamp = System.currentTimeMillis();

        String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
        String bizParam = this.encryptBizParam(JSON.toJSONString(bizParamMap), formInfo.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel", formInfo.getApiKey());
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("content", bizParam);


        log.info("【点贷】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【点贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("status");
        String msg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");

        pushResultDTO.setResult(result);
        pushResultDTO.setCode(String.valueOf(status));
        pushResultDTO.setMessage(UnicodeUtil.toString(msg));
        pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));

        if (ObjectUtil.equal(status, Integer.valueOf(200))) {
            String orderSn = data.getString("order_sn");
            pushResultDTO.setOutOrderNo(orderSn);
            pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
            pushResultDTO.setSuccess(true);// 不接算
        } else {
            pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
            pushResultDTO.setSuccess(false);
        }
        return pushResultDTO;

    }

    /**
     * 获取签名数据
     *
     * @param apiKey
     * @param timestamp
     * @param apiSecret
     * @return
     */
    private String getSignResult(String apiKey, Long timestamp, String apiSecret) {
        String signStr = StrUtil.format("{}{}{}", apiKey, timestamp, apiSecret);
        return SecureUtil.md5(signStr).toLowerCase();
    }


    /**
     * @param content
     * @param key
     * @return
     */
    public String encryptBizParam(String content, String key) throws Exception {
        byte[] originalContent = content.getBytes(StandardCharsets.UTF_8);
        String keys = key.substring(0,16);
        byte[] encryptKey = keys.getBytes();
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");;
            SecretKeySpec skeySpec = new SecretKeySpec(encryptKey, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(originalContent);
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
